//注册
exports.register = function(req, res){
	var mobile = req.body.mobile*1;
	var password = req.body.password;
	var theTime = parseInt((new Date()).valueOf()/1000);
	var ip = req.connection.remoteAddress.replace('::ffff:','');
	//console.log(ip);
	
	if(mobile != "" && password != ""){
		if(!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(mobile)))
			res.end(JSON.stringify({code:'2'}));
		var md5 = require('md5');
		var password = md5(md5(password)+key);
		var mysql = require('mysql');
		var TEST_DATABASE = 'weibang';
		var client = mysql.createConnection(myDb);
		client.connect();
		client.query("use " + myDb.DbName);
		//var client = require("mysql").createConnection(myDb).connect().query("use " + myDb.DbName);
		client.query('SELECT `id`,`passWord` FROM 360_member WHERE mobile = "'+ mobile +'" limit 1',
			//检验用户手机号是否存在
			function selectCb(err, results){
				if (err)
					res.end(JSON.stringify({code:'5'}));
				else{
					if(results.length){
						console.log(results.passWord);
						res.end(JSON.stringify({code:'3'}));
					}
					else{
						//写入新用户
						client.query("INSERT INTO `360_member` (`id`, `mobile`, `nickName`, `passWord`, `headPath`, `area`, `code`, `registrationTime`, `RegisteredIP`, `LandingTime`) VALUES (NULL, '"+mobile+"', '', '"+password+"','', '', '', '"+ theTime +"', '"+ ip +"', '"+ theTime +"');",
							function selectCb(err, inStatus){
								if(!err){
									var newId = inStatus.insertId;
									console.log(newId);
									res.end(JSON.stringify({code:'1',data:{uid:""+newId+""}}));								
								}
								else{
									res.end(JSON.stringify({code:'5'}));
								}
								client.end();
							}
						);
					}
				}
			}
		)
	}
	else{
		res.end(JSON.stringify({code:'2'}));
	}
};


//登陆
exports.login = function(req, res){
	var mobile = req.body.mobile*1;
	var password = req.body.password;
	if(mobile != "" && password != ""){
		var md5 = require('md5');
		var password = md5(md5(password)+key);
		var mysql = require('mysql');
		var client = mysql.createConnection(myDb);
		client.connect();
		client.query("use " + myDb.DbName);
		//var client = require("mysql").createConnection(myDb).connect().query("use " + myDb.DbName);
		client.query('SELECT `id`,`nickName`,`headPath` FROM 360_member WHERE mobile = "'+ mobile +'" and password = "'+password+'" limit 1',
		//检验账号密码是否符合
			function selectCb(err, results, fields){
				if(err)
					res.end(JSON.stringify({code:'5'}));
				else{
					if(results.length){
						var uid = results[0].id;
						var nickName = results[0].nickName;
						var headPath = results[0].headPath;
						var theTime = parseInt((new Date()).valueOf()/1000);
						var urlkey = aes.encode(theTime + "|" + mobile + "|" + uid + "|" + nickName + "|" + headPath,key);
						res.end(JSON.stringify({code:'1',data:{key:urlkey,uid:uid}}));
					}
					else{
						//检验手机号码是否存在
						client.query('SELECT `id` FROM 360_member WHERE mobile = "'+ mobile +'" limit 1',
							function selectCb(err, results, fields){
								if(err)
									res.end(JSON.stringify({code:'5'}));
								else{
									//密码错误
									if(results.length)
										res.end(JSON.stringify({code:'2'}));
									//账号不存在
									else
										res.end(JSON.stringify({code:'3'}));
								}
							}
						)
					}
				}
			}
		)
	}
	else{
		res.end(JSON.stringify({code:'2'}));
	}
};


//用户资料编辑
exports.dataEdit = function(req, res){
		var keycode = req.body.key;
		var keycode = aes.decode(keycode.replace(' ','+'),key);
		var keycode = keycode.split('|');
		
		if(keycode){//验证密钥
			var uid = req.body.uid;
			
			var nickName = req.body.nickName ? req.body.nickName:"";
			var area = req.body.area ? req.body.area : "";
			var sex = req.body.sex ? req.body.sex : "";
			var signature = req.body.signature ? req.body.signature : "";
			var type = req.body.type * 1;
			
			var mysql = require('mysql');
			var client = mysql.createConnection(myDb);
			client.connect();
			client.query("use " + myDb.DbName);	
				if(type==1){
					client.query("UPDATE `360_member` SET  `nickName` = '"+nickName+"' , `area` = '"+area+"' , `signature` =  '"+signature+"' ,`sex` = '"+sex+"' WHERE `id` ="+keycode[2]+" LIMIT 1 ;",
						function selectCb(err, inStatus){
							if(!err)
								res.end(JSON.stringify({code:'1'}));
							else
								res.end(JSON.stringify({code:'2'}));
						}
					)
				}
				else{
					client.query('SELECT `nickName`,`area`,`sex`,`signature` FROM 360_member WHERE id = "'+ keycode[2] +'" limit 1',
						function selectCb(err, data){
							if(!err){
								var returnData = {};
								returnData.code = "1";
								returnData.data = data;
								res.end(JSON.stringify(returnData));
							}	
							else
								res.end(JSON.stringify({code:'2'}));
						}
					)
				}
		}
		else
			res.end(JSON.stringify({code:'2'}));
}

//用户头像更换
exports.headUp = function(req, res){
	var keycode = req.param('key').replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	if(keycode[2]){
		var express = require('express'),
		formidable = require('formidable'),
		async = require('async'),
		md5 = require('md5'),
		fs = require('fs'),
		//上传
		AVATAR_UPLOAD_FOLDER = '/avatar/';
		var form = new formidable.IncomingForm();
		form.encoding = 'utf-8';
		form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;
		form.keepExtensions = true;
		//上传限制 3M;
		form.maxFieldsSize = 3 * 1024 * 1024;
		async.waterfall([
			function(callback){
				form.parse(req, function(err, fields, files){
					if (err)
						res.end(JSON.stringify({code:'1'}));
					var extName = '';  //后缀名
					switch (files.file.type) {
						case 'image/pjpeg':
						extName = 'jpg';
						break;
						case 'image/jpeg':
						extName = 'jpg';
						break;
						case 'image/gif':
						extName = 'gif';
						break;						
						case 'image/png':
						extName = 'png';
						break;
						case 'image/x-png':
						extName = 'png';
						break;	 
					}
					if(extName.length > 0){
						var avatarName = '' + md5(Math.random()).substr(0,14) + '.' + extName;
						var newPath = form.uploadDir + avatarName;
						//重命名
						fs.renameSync(files.file.path, newPath);
						callback(null,AVATAR_UPLOAD_FOLDER+avatarName);
					}
					else{
						//文件格式错误;
						res.send(JSON.stringify({code:'3'}));
						return false;
					}
				});
			},
			function(a1 , callback){
				console.log("UPDATE `360_member` SET `headPath` = '"+a1+"' WHERE `id` ="+keycode[2]+" LIMIT 1");
				var mysql = require('mysql');
				var client = mysql.createConnection(myDb);
				client.connect();
				client.query("use " + myDb.DbName);
				client.query("UPDATE `360_member` SET `headPath` = '"+a1+"' WHERE `id` ="+keycode[2]+" LIMIT 1",
					function selectCb(err, returnData, fields){
						if(!err){
							var reData = {code:"1",data:[{"headPath":a1}]};
							res.send(JSON.stringify(reData));
						}
						else{
							res.send(JSON.stringify({code:'2'}));
						}
					}
				)
			}],
			function (err, result) {
				res.send();
			}
		)
	}
	else
		res.send(JSON.stringify({code:'2'}));
}

